﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;

namespace CIS.Web.Binders
{
	public class ArrayPropertyBinder<T> : IPropertyBinder
	{
		private T GetValue(ModelBindingContext bindingContext, string key)
		{
			ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(key);
			bindingContext.ModelState.SetModelValue(key, valueResult);
			return (T)valueResult.ConvertTo(typeof(T));
		}

		public object BindModel(ControllerContext controllerContext,
							ModelBindingContext bindingContext,
							MemberDescriptor memberDescriptor)
		{
			var queryString = controllerContext.HttpContext.Request.QueryString;
			if (queryString.Count > 0)
			{
				var key = queryString.AllKeys.FirstOrDefault(
					    k => k.Equals(memberDescriptor.Name + "[]"
							, StringComparison.OrdinalIgnoreCase));
				if (key != null)
				{
					return GetValue(bindingContext, key);
				}
			}

			return null;
		}
	}
}